/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.sciEnterprise.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.modelDemand.domain.ModelDemandAuditLog;
import com.fzhucc.modules.sciEnterprise.domain.SciEnterprise;
import com.fzhucc.modules.sciEnterprise.domain.dto.*;
import com.fzhucc.modules.sciPersonnelInfo.domain.SciPersonnelInfo;
import com.fzhucc.modules.sciPersonnelInfo.domain.dto.AllowSciPersonnelInfoDto;
import com.fzhucc.modules.sciPersonnelInfo.domain.dto.AuditSciPersonnelInfoDto;
import com.fzhucc.modules.sciPersonnelInfo.domain.dto.SciPersonnelInfoQueryCriteria;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.system.service.DictDetailService;
import com.fzhucc.modules.system.service.DictService;
import com.fzhucc.modules.system.service.dto.DictDetailDto;
import com.fzhucc.modules.system.service.dto.DictDto;
import com.fzhucc.modules.system.service.dto.DictQueryCriteria;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.sciEnterprise.repository.SciEnterpriseRepository;
import com.fzhucc.modules.sciEnterprise.service.mapstruct.SciEnterpriseMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2024-06-03
 **/
@Service
@RequiredArgsConstructor
public class SciEnterpriseService {

    @Value("${sci.audit.shtg}")
    public String shtg;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    private final SciEnterpriseRepository sciEnterpriseRepository;
    private final SciEnterpriseMapper sciEnterpriseMapper;

    private final DictService dictService;

    private final DictDetailService dictDetailService;

    private final UserRepository userRepository;


    //根据不同设置不同的部门查看
    public String setCriteria(SciEnterpriseQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            //throw new RuntimeException(e);
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && (orgArea.equals(all) || orgArea.equals(all2))) { //如果等于福建省则查全部
                return null;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//用的org组织最高看全部
                return null;
            } else {
                return res.getOrgArea();//如果用户的权限不是福建省则 只能看到对应的组织
            }
        } else {
            return null;
        }
    }

    public Map<String, Object> queryAll(SciEnterpriseQueryCriteria criteria, Pageable pageable) {
        //管理端根据登录用户地区
        String str = setCriteria(criteria);
        if (str == null) {
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length > 0) {
                //表示为省总账号 且输入模糊查询
                //TODO 即查询参数有参数  省总账号查具体模糊查询
                String[] orgAreas = criteria.getOrgAreas();
                criteria.setOrgArea(orgAreas[orgAreas.length - 1]);
            } else {
                criteria.setOrgArea(str);
            }
        } else {
            //TODO 添加判断第三级   是否包含在第二级中   则采用第三级的查询
            if (criteria.getOrgAreas() != null && criteria.getOrgAreas().length == 3) {
                if (str.contains(criteria.getOrgAreas()[1])) {
                    criteria.setOrgArea(criteria.getOrgAreas()[2]);
                }
            } else {
                criteria.setOrgArea(str);
            }
        }
        criteria.setIsDelete(0);
        criteria.setOrgAreas(null);
        Page<SciEnterprise> page = sciEnterpriseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<SciEnterpriseDto> map = page.map(sciEnterpriseMapper::toDto);
        List<SciEnterpriseDto> list = map.getContent();
        if (list!=null && list.size()>0){
            for (SciEnterpriseDto dto:list){
                String orgArea = dto.getOrgArea();
                if (orgArea != null && orgArea.contains(";")) {
                    String[] array = orgArea.split(";");
                    dto.setOrgAreas(array);
                } else {
                    String[] array = {};
                    dto.setOrgAreas(array);
                }

                String companyArea = dto.getCompanyArea();
                if (companyArea != null && companyArea.contains(";")) {
                    String[] array = companyArea.split(";");
                    dto.setCompanyAreas(array);
                } else {
                    String[] array = {};
                    dto.setCompanyAreas(array);
                }
            }
        }
        return PageUtil.toPage(map);
    }

    public Map<String, Object> queryPassEntertpriseByNo(SciEnterpriseQueryCriteria criteria, Pageable pageable) {
        criteria.setAStatus(shtg);
        criteria.setIsDelete(0);
        Page<SciEnterprise> page = sciEnterpriseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(sciEnterpriseMapper::toDto));
    }

    public List<SciEnterpriseDto> queryAll(SciEnterpriseQueryCriteria criteria) {
        criteria.setIsDelete(0);
        return sciEnterpriseMapper.toDto(sciEnterpriseRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Transactional
    public SciEnterpriseDto findById(Integer id) {
        SciEnterprise sciEnterprise = sciEnterpriseRepository.findById(id).orElseGet(SciEnterprise::new);
        ValidationUtil.isNull(sciEnterprise.getId(), "SciEnterprise", "id", id);
        SciEnterpriseDto dto = sciEnterpriseMapper.toDto(sciEnterprise);
        String orgArea = dto.getOrgArea();
        if (orgArea != null && orgArea.contains(";")) {
            String[] array = orgArea.split(";");
            dto.setOrgAreas(array);
        } else {
            String[] array = {};
            dto.setOrgAreas(array);
        }

        String companyArea = dto.getCompanyArea();
        if (companyArea != null && companyArea.contains(";")) {
            String[] array = companyArea.split(";");
            dto.setCompanyAreas(array);
        } else {
            String[] array = {};
            dto.setCompanyAreas(array);
        }
        return dto;
    }

    public List<SciEnterprise> queryPassEntertprise() {
        List<SciEnterprise> list = sciEnterpriseRepository.queryPassEntertprise(shtg);
        return list;
    }

    public List<SciEnterprise> queryPassEntertpriseByName(SciEnterpriseNameQueryCriteria sciEnterpriseNameQueryCriteria) {
        String name = sciEnterpriseNameQueryCriteria.getName();
        if (name == null) {
            List<SciEnterprise> list = sciEnterpriseRepository.queryPassEntertprise(shtg);
            return list;
        } else {
            List<SciEnterprise> list = sciEnterpriseRepository.queryPassEntertpriseByName(shtg,"%" + name + "%");
            return list;
        }
    }

    public List<DictDetailDto> getQyAuditStatus() {
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("qy_audit_status");
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            return list1;
        }
        return null;
    }

    public List<DictDetailDto> getCraftsmanEnterpriseProperty() {
        DictQueryCriteria dictQueryCriteria = new DictQueryCriteria();
        dictQueryCriteria.setBlurry("craftsman_enterprise_property");
        List<DictDto> list = dictService.queryAll(dictQueryCriteria);
        if (list != null && list.size() == 1) {
            List<DictDetailDto> list1 = dictDetailService.getDictByDictId(list.get(0).getId());
            return list1;
        }
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    public SciEnterpriseDto create(SciEnterpriseAddDto dto) {
        SciEnterprise sciEnterprise = new SciEnterprise();
        if (dto.getCompanyAreas() != null && dto.getCompanyAreas().length > 0) {
            String last = "";
            for (String a : dto.getCompanyAreas()) {
                last = last + a + ";";
            }
            sciEnterprise.setCompanyArea(last);
        } else {
            sciEnterprise.setCompanyArea(null);
        }
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            sciEnterprise.setOrgArea(last);
        } else {
            sciEnterprise.setOrgArea(orgAreaReturn());
        }
        String name = dto.getName();
        List<SciEnterprise> listEName = sciEnterpriseRepository.queryEntertpriseByName(name);
        if (listEName!=null && listEName.size()>0){
            throw new BadRequestException("已存在企业名称相同的情况,无法注册");
        }
        sciEnterprise.setName(name);
        sciEnterprise.setCode(dto.getCode());
        sciEnterprise.setAStatus("待审核");
        sciEnterprise.setIsDelete(0);
        sciEnterprise.setIsEdit(0);
        sciEnterprise.setDetails(dto.getDetails());
        sciEnterprise.setIsZxw(dto.getIsZxw());
        sciEnterprise.setIsZj(dto.getIsZj());
        sciEnterprise.setNature(dto.getNature());
        sciEnterprise.setLegalRepresentative(dto.getLegalRepresentative());
        sciEnterprise.setDetailAddress(dto.getDetailAddress());
        sciEnterprise.setEstablishedTime(dto.getEstablishedTime());
        SciEnterprise enterprise = sciEnterpriseRepository.save(sciEnterprise);
        SciEnterpriseDto sciEnterpriseDto = sciEnterpriseMapper.toDto(enterprise);
        String orgArea2 = sciEnterpriseDto.getOrgArea();
        if (orgArea2 != null && orgArea2.contains(";")) {
            String[] array = orgArea2.split(";");
            sciEnterpriseDto.setOrgAreas(array);
        } else {
            String[] array = {};
            sciEnterpriseDto.setOrgAreas(array);
        }
        String companyArea = sciEnterpriseDto.getCompanyArea();
        if (companyArea != null && companyArea.contains(";")) {
            String[] array = companyArea.split(";");
            sciEnterpriseDto.setCompanyAreas(array);
        } else {
            String[] array = {};
            sciEnterpriseDto.setCompanyAreas(array);
        }
        return sciEnterpriseDto;
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(SciEnterpriseEditDto dto) {
        SciEnterprise sciEnterprise = sciEnterpriseRepository.findById(dto.getId()).orElseGet(SciEnterprise::new);
        ValidationUtil.isNull(sciEnterprise.getId(), "SciEnterprise", "id", dto.getId());

        if (dto.getCompanyAreas() != null && dto.getCompanyAreas().length > 0) {
            String last = "";
            for (String a : dto.getCompanyAreas()) {
                last = last + a + ";";
            }
            sciEnterprise.setCompanyArea(last);
        } else {
            sciEnterprise.setCompanyArea(null);
        }
        if (dto.getOrgAreas() != null && dto.getOrgAreas().length > 0) {
            String last = "";
            for (String a : dto.getOrgAreas()) {
                last = last + a + ";";
            }
            sciEnterprise.setOrgArea(last);
        } else {
            sciEnterprise.setOrgArea(orgAreaReturn());
        }
        //TODO 新的名称和原来不一样才进行判断
        if (!sciEnterprise.getName().equals(dto.getName())){
            List<SciEnterprise> listEName = sciEnterpriseRepository.queryEntertpriseByName(dto.getName());
            if (listEName!=null && listEName.size()>0){
                throw new BadRequestException("已存在企业名称相同的情况,无法编辑");
            }
        }
        sciEnterprise.setName(dto.getName());
        sciEnterprise.setCode(dto.getCode());
        sciEnterprise.setDetails(dto.getDetails());
        sciEnterprise.setIsZxw(dto.getIsZxw());
        sciEnterprise.setIsZj(dto.getIsZj());
        sciEnterprise.setNature(dto.getNature());
        sciEnterprise.setLegalRepresentative(dto.getLegalRepresentative());
        sciEnterprise.setDetailAddress(dto.getDetailAddress());
        sciEnterprise.setEstablishedTime(dto.getEstablishedTime());
        sciEnterpriseRepository.save(sciEnterprise);
    }

    public String orgAreaReturn() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {//未登录则外面传进来
            return "";
        } else {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            return res.getOrgArea();
        }
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            //sciEnterpriseRepository.deleteById(id);
            Optional<SciEnterprise> res = sciEnterpriseRepository.findById(id);
            if (res.isPresent()) {
                SciEnterprise sciEnterprise = res.get();
                sciEnterprise.setIsDelete(1);
                sciEnterpriseRepository.save(sciEnterprise);
            }
        }
    }

    public void download(List<SciEnterpriseDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SciEnterpriseDto sciEnterprise : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("企业名称", sciEnterprise.getName());
            map.put("统一社会信用码", sciEnterprise.getCode());
            map.put("地区组织机构区分  ", sciEnterprise.getOrgArea());
            map.put("是否删除默认否", sciEnterprise.getIsDelete());
            map.put("审核状态  字典qy_audit_status", sciEnterprise.getAStatus());
            map.put("企业性质  字典craftsman_enterprise_property", sciEnterprise.getNature());
            map.put("企业所在区域  ", sciEnterprise.getCompanyArea());
            map.put("法定代表人", sciEnterprise.getLegalRepresentative());
            map.put("企业详细地址", sciEnterprise.getDetailAddress());
            map.put("企业成立时间（格式yyyy-MM-dd）", sciEnterprise.getEstablishedTime());
            map.put("企业简介", sciEnterprise.getDetails());
            map.put("是否为专精特新企业", sciEnterprise.getIsZj());
            map.put("是否为中小微企业", sciEnterprise.getIsZxw());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Transactional(rollbackFor = Exception.class)
    public void auditQy(AuditEnterpriseDto dto) {
        Optional<SciEnterprise> res = sciEnterpriseRepository.findById(dto.getId());
        if (!res.isPresent()) {
            throw new BadRequestException("未找到企业id");
        }
        String cAuditStatus = dto.getAuditStatus();
        if (cAuditStatus == null || cAuditStatus.equals("")) {
            throw new BadRequestException("缺少审核状态");
        }
        if (!cAuditStatus.contains("审核")){
            throw new BadRequestException("不允许的审核状态");
        }
        SciEnterprise qy = res.get();
        qy.setAStatus(cAuditStatus);
        if (cAuditStatus.contains(shtg)){
            if (qy.getIsEdit() == 1) {

            } else {
                qy.setIsEdit(0); //打开了允许编辑就不管他 否住则设置为不可编辑
            }
        }else if(cAuditStatus.contains("审核拒绝")){
            qy.setIsEdit(1);
        }else if(cAuditStatus.contains("待审核")){
            if (qy.getIsEdit() == 1) {

            } else {
                qy.setIsEdit(0); //打开了允许编辑就不管他 否住则设置为不可编辑
            }
        }else{

        }
        sciEnterpriseRepository.save(qy);
    }

    @Transactional(rollbackFor = Exception.class)
    public void isAllowEdit(AllowEnterpriseDto dto) {
        Optional<SciEnterprise> res = sciEnterpriseRepository.findById(dto.getId());
        if (!res.isPresent()) {
            throw new BadRequestException("未找到企业id");
        }
        Integer isEdit = dto.getIsEdit();
        if (isEdit == null) {
            throw new BadRequestException("缺少参数");
        }
        if (isEdit != 0 && isEdit != 1) {
            throw new BadRequestException("参数错误无法操作");
        }
        SciEnterprise qy = res.get();
        qy.setIsEdit(isEdit);
        sciEnterpriseRepository.save(qy);
    }
}